<?php

namespace common\domain\components\actions;

use common\domain\base\ApiResponse;
use common\domain\helper\Request;
use Yii;
use yii\base\Model;
use yii\db\ActiveRecord;
use yii\rest\Action;
use yii\web\NotFoundHttpException;
use yii\web\ServerErrorHttpException;

class UpdateAction extends Action
{
    use ApiResponse;

    public $scenario = Model::SCENARIO_DEFAULT;

    /**
     * @return array
     * @throws ServerErrorHttpException
     * @throws \yii\base\InvalidConfigException
     */
    public function run(): array
    {
        $id = Request::getRequest('id');
        try {
            $model = $this->findModel($id);
        } catch (NotFoundHttpException $ex) {
            return $this->responseError('操作失败!，数据不存在！');
        }

        if ($this->checkAccess) {
            call_user_func($this->checkAccess, $this->id, $model);
        }

        $model->scenario = $this->scenario;
        $model->load(Yii::$app->getRequest()->getBodyParams(), '');
        if ($model->save() === false && !$model->hasErrors()) {
            throw new ServerErrorHttpException('未知原因，更新失败！');
        }

        $msg = $model->getFirstErrors();
        if (!empty($msg)) {
            return $this->responseError('输入错误', $msg);
        }

        return $this->responseSuccess($model);
    }
}
